{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Tce3stUlHN0L"
      },
      "source": [
        "##### Copyright 2025 Google LLC."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "tuOe1ymfHZPu"
      },
      "outputs": [],
      "source": [
        "# @title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "oJt4OFKPgO8C"
      },
      "source": [
        "# Search re-ranking using Gemini embeddings"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "k5n0sCc_fKcB"
      },
      "source": [
        "<a target=\"_blank\" href=\"https://colab.research.google.com/github/google-gemini/cookbook/blob/main/examples/Search_reranking_using_embeddings.ipynb\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" height=30/></a>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "bbf4f2c17530"
      },
      "source": [
        "<!-- Princing warning Badge -->\n",
        "<table>\n",
        "  <tr>\n",
        "    <!-- Emoji -->\n",
        "    <td bgcolor=\"#f5949e\">\n",
        "      <font size=30>⚠️</font>\n",
        "    </td>\n",
        "    <!-- Text Content Cell -->\n",
        "    <td bgcolor=\"#f5949e\">\n",
        "      <h3><font color=black>This notebook requires paid tier rate limits to run properly.<br>  \n",
        "(cf. <a href=\"https://ai.google.dev/pricing#veo2\"><font color='#217bfe'>pricing</font></a> for more details).</font></h3>\n",
        "    </td>\n",
        "  </tr>\n",
        "</table>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "0UO0Cgq0mRlG"
      },
      "source": [
        "This notebook demonstrates the use of embeddings to re-rank search results. This walkthrough will focus on the following objectives:\n",
        "\n",
        "\n",
        "\n",
        "1.   Setting up your development environment and API access to use Gemini.\n",
        "2.   Using Gemini's function calling support to access the Wikipedia API.\n",
        "3.   Embedding content via Gemini API.\n",
        "4.   Re-ranking the search results.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "-e5Aje-DTQOq"
      },
      "source": [
        "This is how you will implement search re-ranking:\n",
        "\n",
        "\n",
        "1.   The user will make a search query.\n",
        "2.   You will use Wikipedia API to return the relevant search results.\n",
        "3.   The search results will be embedded and their relevance will be evaluated by calculating distance metrics like cosine similarity.\n",
        "4.   The most relevant search result will be returned as the final answer."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "rpVL_QrF5-oF"
      },
      "source": [
        "> The non-source code materials in this notebook are licensed under Creative Commons - Attribution-ShareAlike CC-BY-SA 4.0, https://creativecommons.org/licenses/by-sa/4.0/legalcode."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "pwImlRg9DUp7"
      },
      "source": [
        "## Setup\n",
        "\n",
        "First, download and install the Gemini API Python library."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "metadata": {
        "id": "Nv_6f_qNHe_2"
      },
      "outputs": [],
      "source": [
        "!pip install -U -q google-genai"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "d3b7ab5e6c09"
      },
      "source": [
        "Also install the `wikipedia` package that will be used during this tutorial."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "metadata": {
        "id": "5999faf240a4"
      },
      "outputs": [],
      "source": [
        "!pip install -U -q wikipedia"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "739f0bb73f05"
      },
      "source": [
        "Note: The [`wikipedia` package](https://pypi.org/project/wikipedia/) notes that it was \"designed for ease of use and simplicity, not for advanced use\", and that production or heavy use should instead \"use [Pywikipediabot](http://www.mediawiki.org/wiki/Manual:Pywikipediabot) or one of the other more advanced [Python MediaWiki API wrappers](http://en.wikipedia.org/wiki/Wikipedia:Creating_a_bot#Python)\"."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 11,
      "metadata": {
        "id": "D0qOtLI3FVid"
      },
      "outputs": [],
      "source": [
        "import json\n",
        "import textwrap\n",
        "\n",
        "from google import genai\n",
        "from google.genai import types\n",
        "\n",
        "import wikipedia\n",
        "from wikipedia.exceptions import DisambiguationError, PageError\n",
        "\n",
        "import numpy as np\n",
        "\n",
        "from IPython.display import Markdown\n",
        "\n",
        "def to_markdown(text):\n",
        "  text = text.replace('•', '  *')\n",
        "  return Markdown(textwrap.indent(text, '> ', predicate=lambda _: True))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "aeo_9J9iDtCx"
      },
      "source": [
        "### Grab an API Key\n",
        "\n",
        "Before you can use the Gemini API, you must first obtain an API key. If you don't already have one, create a key with one click in Google AI Studio.\n",
        "\n",
        "<a class=\"button button-primary\" href=\"https://aistudio.google.com/app/apikey\" target=\"_blank\" rel=\"noopener noreferrer\">Get an API key</a>\n",
        "\n",
        "In Colab, add the key to the secrets manager under the \"🔑\" in the left panel. Give it the name `GEMINI_API_KEY`.\n",
        "\n",
        "Once you have the API key, pass it to the SDK. You can do this in two ways:\n",
        "\n",
        "* Put the key in the `GEMINI_API_KEY` environment variable (the SDK will automatically pick it up from there).\n",
        "* Pass the key to `genai.Client(api_key=...)`"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "yxzEH0GqLshI"
      },
      "outputs": [],
      "source": [
        "from google.colab import userdata\n",
        "\n",
        "# Or use `os.getenv('GEMINI_API_KEY')` to fetch an environment variable.\n",
        "GEMINI_API_KEY=userdata.get('GEMINI_API_KEY')\n",
        "\n",
        "client = genai.Client(api_key=GEMINI_API_KEY)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "6f098c05d0eb"
      },
      "source": [
        "### Select the model to be used"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 7,
      "metadata": {
        "id": "264eb6be278e"
      },
      "outputs": [],
      "source": [
        "MODEL_ID = \"gemini-2.5-flash\" # @param [\"gemini-2.5-flash-lite\", \"gemini-2.5-flash\", \"gemini-2.5-pro\",\"gemini-3-pro-preview\"] {\"allow-input\":true, isTemplate: true}"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "0hkJSFIWI7G1"
      },
      "source": [
        "## Define tools"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "7HjN6hsAJkOq"
      },
      "source": [
        "As stated earlier, this tutorial uses Gemini's function calling support to access the Wikipedia API. Please refer to the [docs](https://ai.google.dev/docs/function_calling) to learn more about function calling."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "fpFkazXUenkK"
      },
      "source": [
        "### Define the search function"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "2fp-m-5Ke0XY"
      },
      "source": [
        "To cater to the search engine needs, you will design this function in the following way:\n",
        "\n",
        "\n",
        "*   For each search query, the search engine will use the `wikipedia.search` method to get relevant topics.\n",
        "*   From the relevant topics, the engine will choose `n_topics(int)` top candidates and will use `gemini-2.5-flash` to extract relevant information from the page.\n",
        "*   The engine will avoid duplicate entries by maintaining a search history.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 8,
      "metadata": {
        "id": "2U27tdP8OBys"
      },
      "outputs": [],
      "source": [
        "def wikipedia_search(search_queries: list[str]) -> list[str]:\n",
        "  \"\"\"Search wikipedia for each query and summarize relevant docs.\"\"\"\n",
        "  n_topics=3\n",
        "  search_history = set() # tracking search history\n",
        "  search_urls = []\n",
        "  summary_results = []\n",
        "\n",
        "  for query in search_queries:\n",
        "    print(f'Searching for \"{query}\"')\n",
        "    search_terms = wikipedia.search(query)\n",
        "\n",
        "    print(f\"Related search terms: {search_terms[:n_topics]}\")\n",
        "    for search_term in search_terms[:n_topics]: # select first `n_topics` candidates\n",
        "      if search_term in search_history: # check if the topic is already covered\n",
        "        continue\n",
        "\n",
        "      print(f'Fetching page: \"{search_term}\"')\n",
        "      search_history.add(search_term) # add to search history\n",
        "\n",
        "      try:\n",
        "        # extract the relevant data by using `gemini-2.0-flash` model\n",
        "        page = wikipedia.page(search_term, auto_suggest=False)\n",
        "        url = page.url\n",
        "        print(f\"Information Source: {url}\")\n",
        "        search_urls.append(url)\n",
        "        page = page.content\n",
        "        response = client.models.generate_content(\n",
        "            model=MODEL_ID,\n",
        "            contents=textwrap.dedent(f\"\"\"\\\n",
        "                Extract relevant information\n",
        "                about user's query: {query}\n",
        "                From this source:\n",
        "\n",
        "                {page}\n",
        "\n",
        "                Note: Do not summarize. Only Extract and return the relevant information\n",
        "        \"\"\"))\n",
        "\n",
        "        urls = [url]\n",
        "        if response.candidates[0].citation_metadata:\n",
        "          extra_citations = response.candidates[0].citation_metadata.citation_sources\n",
        "          extra_urls = [source.url for source in extra_citations]\n",
        "          urls.extend(extra_urls)\n",
        "          search_urls.extend(extra_urls)\n",
        "          print(\"Additional citations:\", response.candidates[0].citation_metadata.citation_sources)\n",
        "        try:\n",
        "          text = response.text\n",
        "        except ValueError:\n",
        "          pass\n",
        "        else:\n",
        "          summary_results.append(text + \"\\n\\nBased on:\\n  \" + ',\\n  '.join(urls))\n",
        "\n",
        "      except DisambiguationError:\n",
        "        print(f\"\"\"Results when searching for \"{search_term}\" (originally for \"{query}\")\n",
        "        were ambiguous, hence skipping\"\"\")\n",
        "        continue\n",
        "\n",
        "      except PageError:\n",
        "        print(f'{search_term} did not match with any page id, hence skipping.')\n",
        "        continue\n",
        "        \n",
        "      except:\n",
        "        print(f'{search_term} did not match with any page id, hence skipping.')\n",
        "        continue\n",
        "\n",
        "  print(f\"Information Sources:\")\n",
        "  for url in search_urls:\n",
        "    print('    ', url)\n",
        "\n",
        "  return summary_results\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 9,
      "metadata": {
        "id": "EWKkkKDXmzOX"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Searching for \"What are LLMs?\"\n",
            "Related search terms: ['Large language model', 'Retrieval-augmented generation', 'Gemini (chatbot)']\n",
            "Fetching page: \"Large language model\"\n",
            "Information Source: https://en.wikipedia.org/wiki/Large_language_model\n",
            "Fetching page: \"Retrieval-augmented generation\"\n",
            "Information Source: https://en.wikipedia.org/wiki/Retrieval-augmented_generation\n",
            "Fetching page: \"Gemini (chatbot)\"\n",
            "Information Source: https://en.wikipedia.org/wiki/Gemini_(chatbot)\n",
            "Information Sources:\n",
            "     https://en.wikipedia.org/wiki/Large_language_model\n",
            "     https://en.wikipedia.org/wiki/Retrieval-augmented_generation\n",
            "     https://en.wikipedia.org/wiki/Gemini_(chatbot)\n"
          ]
        }
      ],
      "source": [
        "example = wikipedia_search([\"What are LLMs?\"])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "8bPT114QEPgW"
      },
      "source": [
        "Here is what the search results look like:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 10,
      "metadata": {
        "id": "8wy7YUFqEYTv"
      },
      "outputs": [
        {
          "data": {
            "text/markdown": [
              "> A large language model (LLM) is a language model trained with self-supervised machine learning on a vast amount of text, designed for natural language processing tasks, especially language generation.\n",
              "> The largest and most capable LLMs are generative pretrained transformers (GPTs).\n",
              "> LLMs can be fine-tuned for specific tasks or guided by prompt engineering.\n",
              "> These models acquire predictive power regarding syntax, semantics, and ontologies inherent in human language corpora, but they also inherit inaccuracies and biases present in the data they are trained in.\n",
              "> An LLM is a type of foundation model (large X model) trained on language.\n",
              "> LLMs are generally based on the transformer architecture.\n",
              "> Typically, LLMs are trained with single- or half-precision floating point numbers (float32 and float16).\n",
              "> The qualifier \"large\" in \"large language model\" is inherently vague, as there is no definitive threshold for the number of parameters required to qualify as \"large\".\n",
              "> \n",
              "> Based on:\n",
              ">   https://en.wikipedia.org/wiki/Large_language_model"
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "data": {
            "text/markdown": [
              "> Large language models (LLMs) are a type of model that rely on static training data. They have pre-existing training data and an internal representation of this data. LLMs can generate responses, output, or synthesize answers to user queries. However, LLMs can provide incorrect information, generate misinformation, or hallucinate. They may also struggle to recognize when they lack sufficient information to provide a reliable response, or misinterpret the context of information they retrieve.\n",
              "> \n",
              "> Based on:\n",
              ">   https://en.wikipedia.org/wiki/Retrieval-augmented_generation"
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "data": {
            "text/markdown": [
              "> *   **Definition/Nature:**\n",
              ">     *   Generative artificial intelligence chatbots (like Gemini and ChatGPT) are \"based on\" large language models (LLMs).\n",
              ">     *   Gemini is described as a \"multimodal and more powerful LLM touted as the company's 'largest and most capable AI model'.\"\n",
              "> *   **Examples of LLMs mentioned:**\n",
              ">     *   GPT-3 family\n",
              ">     *   LaMDA (a prototype LLM)\n",
              ">     *   PaLM (a newer and more powerful LLM from Google)\n",
              ">     *   Gemini\n",
              "> \n",
              "> Based on:\n",
              ">   https://en.wikipedia.org/wiki/Gemini_(chatbot)"
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "from IPython.display import display\n",
        "\n",
        "for e in example:\n",
        "  display(to_markdown(e))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "SKcH1LICeg5Z"
      },
      "source": [
        "### Pass the tools to the model"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "qQcxR7cjLjGM"
      },
      "source": [
        "If you pass a list of functions to the `GenerativeModel`'s `tools` argument,\n",
        "it will extract a schema from the function's signature and type hints, and then pass schema along to the API calls. In response the model may return a `FunctionCall` object asking to call the function.\n",
        "\n",
        "Note: This approach only handles annotations of `AllowedTypes = int | float | str | dict | list['AllowedTypes']`\n",
        "\n",
        "The request to the Gemini model will keep a reference to the function inself, so that it _can_ execute the function locally later."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "VedPbpzlh6jX"
      },
      "source": [
        "## Generate supporting search queries"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "5sLKZik7isBW"
      },
      "source": [
        "In order to have multiple supporting search queries to the user's original query, you will ask the model to generate more such queries. This would help the engine to cover the asked question on comprehensive levels."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 16,
      "metadata": {
        "id": "Z-Ym3H9KIosY"
      },
      "outputs": [],
      "source": [
        "instructions = \"\"\"You have access to the Wikipedia API which you will be using\n",
        "to answer a user's query. Your job is to generate a list of search queries which\n",
        "might answer a user's question. Be creative by using various key-phrases from\n",
        "the user's query. To generate variety of queries, ask questions which are\n",
        "related to  the user's query that might help to find the answer. The more\n",
        "queries you generate the better are the odds of you finding the correct answer.\n",
        "Here is an example:\n",
        "\n",
        "user: Tell me about Cricket World cup 2023 winners.\n",
        "\n",
        "function_call: wikipedia_search(['What is the name of the team that\n",
        "won the Cricket World Cup 2023?', 'Who was the captain of the Cricket World Cup\n",
        "2023 winning team?', 'Which country hosted the Cricket World Cup 2023?', 'What\n",
        "was the venue of the Cricket World Cup 2023 final match?', 'Cricket World cup 2023',\n",
        "'Who lifted the Cricket World Cup 2023 trophy?'])\n",
        "\n",
        "The search function will return a list of article summaries, use these to\n",
        "answer the  user's question.\n",
        "\n",
        "Here is the user's query: {query}\n",
        "\"\"\""
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "3Wyn3lV-d5S_"
      },
      "source": [
        "In order to yield creative and a more random variety of questions, you will set the model's temperature parameter to a value higher. Values can range from [0.0,1.0], inclusive. A value closer to 1.0 will produce responses that are more varied and creative, while a value closer to 0.0 will typically result in more straightforward responses from the model."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "TD1vU6FXhYO5"
      },
      "source": [
        "## Enable automatic function calling and call the API"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "qyUSnXJ5hg6x"
      },
      "source": [
        "Now start a new chat with `enable_automatic_function_calling=True`. With it enabled, the `genai.ChatSession` will handle the back and forth required to call the function, and return the final response:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 15,
      "metadata": {
        "id": "39kqTnBRLDeQ"
      },
      "outputs": [],
      "source": [
        "tools = [wikipedia_search]\n",
        "\n",
        "config = types.GenerateContentConfig(\n",
        "    temperature=0.6,\n",
        "    tools=tools\n",
        ")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 18,
      "metadata": {
        "id": "ZNJqA60yKNpT"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Searching for \"Deep-sea life survival strategies\"\n",
            "Related search terms: ['Sea of Thieves', 'Thalassophobia', 'Whalefall (novel)']\n",
            "Fetching page: \"Sea of Thieves\"\n",
            "Information Source: https://en.wikipedia.org/wiki/Sea_of_Thieves\n",
            "Fetching page: \"Thalassophobia\"\n",
            "Information Source: https://en.wikipedia.org/wiki/Thalassophobia\n",
            "Fetching page: \"Whalefall (novel)\"\n",
            "Information Source: https://en.wikipedia.org/wiki/Whalefall_(novel)\n",
            "Searching for \"Adaptations of deep-sea organisms\"\n",
            "Related search terms: ['Deep-sea fish', 'Deep sea', 'Deep-sea gigantism']\n",
            "Fetching page: \"Deep-sea fish\"\n",
            "Information Source: https://en.wikipedia.org/wiki/Deep-sea_fish\n",
            "Fetching page: \"Deep sea\"\n",
            "Information Source: https://en.wikipedia.org/wiki/Deep_sea\n",
            "Fetching page: \"Deep-sea gigantism\"\n",
            "Information Source: https://en.wikipedia.org/wiki/Deep-sea_gigantism\n",
            "Searching for \"How do deep-sea creatures survive extreme pressure?\"\n",
            "Related search terms: ['Deep-sea community', 'Deep sea', 'Deep-sea fish']\n",
            "Fetching page: \"Deep-sea community\"\n",
            "Information Source: https://en.wikipedia.org/wiki/Deep-sea_community\n",
            "Searching for \"Food sources in the deep sea\"\n",
            "Related search terms: ['Deep-sea fish', 'Deep-sea community', 'Deep sea']\n",
            "Searching for \"Chemosynthesis deep sea\"\n",
            "Related search terms: ['Deep-sea community', 'Deep sea', 'Hydrothermal vent']\n",
            "Fetching page: \"Hydrothermal vent\"\n",
            "Information Source: https://en.wikipedia.org/wiki/Hydrothermal_vent\n",
            "Searching for \"Hydrothermal vents deep sea life\"\n",
            "Related search terms: ['Hydrothermal vent', 'Deep-sea community', 'Deep sea']\n",
            "Searching for \"Marine snow deep sea\"\n",
            "Related search terms: ['Marine snow', 'Deep sea', 'Deep-sea gigantism']\n",
            "Fetching page: \"Marine snow\"\n",
            "Information Source: https://en.wikipedia.org/wiki/Marine_snow\n",
            "Searching for \"Bioluminescence deep sea life\"\n",
            "Related search terms: ['Deep sea', 'Deep-sea fish', 'Life That Glows']\n",
            "Fetching page: \"Life That Glows\"\n",
            "Information Source: https://en.wikipedia.org/wiki/Life_That_Glows\n",
            "Searching for \"Deep-sea fish adaptations\"\n",
            "Related search terms: ['Deep-sea fish', 'Deep sea', 'Deep-sea community']\n",
            "Searching for \"Deep-sea environment conditions\"\n",
            "Related search terms: ['Deep-sea gigantism', 'Deep sea', 'Deep-sea fish']\n",
            "Searching for \"What do deep-sea animals eat?\"\n",
            "Related search terms: ['Deep-sea community', 'Deep-sea fish', 'Sea urchin']\n",
            "Fetching page: \"Sea urchin\"\n",
            "Information Source: https://en.wikipedia.org/wiki/Sea_urchin\n",
            "Searching for \"Deep-sea extremophiles\"\n",
            "Related search terms: ['Hydrothermal vent', 'Deep-sea community', 'Oceanic trench']\n",
            "Fetching page: \"Oceanic trench\"\n",
            "Information Source: https://en.wikipedia.org/wiki/Oceanic_trench\n",
            "Information Sources:\n",
            "     https://en.wikipedia.org/wiki/Sea_of_Thieves\n",
            "     https://en.wikipedia.org/wiki/Thalassophobia\n",
            "     https://en.wikipedia.org/wiki/Whalefall_(novel)\n",
            "     https://en.wikipedia.org/wiki/Deep-sea_fish\n",
            "     https://en.wikipedia.org/wiki/Deep_sea\n",
            "     https://en.wikipedia.org/wiki/Deep-sea_gigantism\n",
            "     https://en.wikipedia.org/wiki/Deep-sea_community\n",
            "     https://en.wikipedia.org/wiki/Hydrothermal_vent\n",
            "     https://en.wikipedia.org/wiki/Marine_snow\n",
            "     https://en.wikipedia.org/wiki/Life_That_Glows\n",
            "     https://en.wikipedia.org/wiki/Sea_urchin\n",
            "     https://en.wikipedia.org/wiki/Oceanic_trench\n"
          ]
        }
      ],
      "source": [
        "chat = client.chats.create(\n",
        "    model=\"gemini-2.5-flash\",\n",
        "    config=config\n",
        ")\n",
        "\n",
        "query = \"Explain how deep-sea life survives.\"\n",
        "\n",
        "res = chat.send_message(instructions.format(query=query))"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 19,
      "metadata": {
        "id": "1l8KWb13M_lJ"
      },
      "outputs": [
        {
          "name": "stderr",
          "output_type": "stream",
          "text": [
            "Warning: there are non-text parts in the response: ['thought_signature'], returning concatenated text result from text parts. Check the full candidates.content.parts accessor to get the full model response.\n"
          ]
        },
        {
          "data": {
            "text/markdown": [
              "> Deep-sea life has evolved remarkable adaptations to survive the harsh conditions of its environment, characterized by immense pressure, perpetual darkness, extremely cold temperatures, and scarce food resources.\n",
              "> \n",
              "> Here's how deep-sea organisms manage to thrive:\n",
              "> \n",
              "> 1.  **Pressure Adaptations:**\n",
              ">     *   **Internal Pressure Equalization:** Deep-sea creatures maintain an internal body pressure that is equal to the external hydrostatic pressure, preventing them from being crushed.\n",
              ">     *   **Flexible Bodies:** Many species have gelatinous, watery flesh with minimal bone structure and reduced tissue density. This allows their bodies to compress without damage.\n",
              ">     *   **Absence of Gas-Filled Spaces:** Most deep-sea fish lack swim bladders (gas-filled organs used for buoyancy in shallower waters) as these would collapse under pressure. Instead, some use lipid-rich tissues or have hydrofoil-like fins for lift.\n",
              ">     *   **Molecular Adaptations:** At a cellular level, their proteins and enzymes are specially adapted to function under high pressure, often being more rigid or having modified structures (e.g., increased salt bridges in actin, higher proportion of unsaturated fatty acids in cell membranes to maintain fluidity). Some use osmolytes like Trimethylamine N-oxide (TMAO) to protect proteins.\n",
              "> \n",
              "> 2.  **Food Acquisition:**\n",
              ">     *   **Marine Snow:** In the vast majority of the deep sea, the primary food source is \"marine snow\"—a continuous shower of organic detritus (dead organisms, fecal pellets, etc.) falling from the productive upper layers of the ocean. Organisms filter this snow or scavenge larger food falls.\n",
              ">     *   **Chemosynthesis:** Around hydrothermal vents and cold seeps, life thrives independently of sunlight through chemosynthesis. Specialized bacteria and archaea convert chemical compounds (like hydrogen sulfide and methane) from the Earth's interior into organic matter. These microorganisms form the base of the food web, supporting dense communities of unique organisms, often through symbiotic relationships (e.g., tube worms hosting chemosynthetic bacteria).\n",
              ">     *   **Efficient Feeding:** Due to food scarcity, many deep-sea fish have slow metabolisms and unspecialized diets, preferring to \"sit and wait\" for prey. They often possess large, hinged, and extensible jaws with sharp, recurved teeth to engulf prey of their own size or larger.\n",
              "> \n",
              "> 3.  **Light and Sensory Adaptations:**\n",
              ">     *   **Bioluminescence:** In the absence of sunlight, many deep-sea creatures produce their own light through bioluminescence. This is used for various purposes: attracting prey (like the anglerfish's glowing lure), finding mates, deterring predators (e.g., by startling or counter-illuminating their undersides to blend with faint overhead light), and communication.\n",
              ">     *   **Enhanced Vision:** While some deep-sea fish are blind, others have exceptionally large, tubular eyes with highly sensitive rod cells that are adapted to detect the faintest flickers of bioluminescence or silhouettes against the dim light from above.\n",
              ">     *   **Other Senses:** Given the limited utility of sight, deep-sea organisms heavily rely on other senses. They possess highly developed lateral line systems to detect changes in water pressure and vibrations, an acute sense of smell (olfactory system) to locate food or mates, and sensitive inner ears. Many also have long feelers or tentacles to navigate and find prey in the darkness.\n",
              "> \n",
              "> 4.  **Metabolic and Physical Adaptations:**\n",
              ">     *   **Slow Metabolism:** To conserve energy in a food-scarce environment, deep-sea organisms generally have very slow metabolisms and often grow slowly and live long lives.\n",
              ">     *   **Body Shape and Movement:** Their bodies are often elongated with weak, watery muscles and minimal skeletal structures, which allows them to remain suspended in water with little energy expenditure. Their body shapes are generally better suited for periodic bursts of swimming rather than continuous movement.\n",
              ">     *   **Deep-Sea Gigantism:** Some deep-sea species exhibit gigantism, growing much larger than their shallow-water relatives. This is thought to be an adaptation to colder temperatures, food scarcity (larger size improves foraging ability and metabolic efficiency), and reduced predation pressure.\n",
              "> \n",
              "> 5.  **Reproduction:**\n",
              ">     *   Finding a mate in the vast, dark deep sea can be challenging. Adaptations include hermaphroditism (being both male and female) or unique reproductive strategies, such as the parasitic male anglerfish, which permanently attaches to the female, ensuring a mate is always available."
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "execution_count": 19,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "to_markdown(res.text)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "A0CfKMjYFSQm"
      },
      "source": [
        "That looks like it worked. You can go through the chat history to see the details of what was sent and received in the function calls:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 28,
      "metadata": {
        "id": "_9h2b8saNnxh"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "user -> {\n",
            "  \"text\": \"You have access to the Wikipedia API which you will be using\\nto answer a user's query. Your job is to generate a list of search queries which\\nmight answer a user's question. Be creative by using various key-phrases from\\nthe user's query. To generate variety of queries, ask questions which are\\nrelated to  the user's query that might help to find the answer. The more\\nqueries you generate the better are the odds of you finding the correct answer.\\nHere is an example:\\n\\nuser: Tell me about Cricket World cup 2023 winners.\\n\\nfunction_call: wikipedia_search(['What is the name of the team that\\nwon the Cricket World Cup 2023?', 'Who was the captain of the Cricket World Cup\\n2023 winning team?', 'Which country hosted the Cricket World Cup 2023?', 'What\\nwas the venue of the Cricket World Cup 2023 final match?', 'Cricket World cup 2023',\\n'Who lifted the Cricket World Cup 2023 trophy?'])\\n\\nThe search function will return a list of article summaries, use these to\\nanswer the  user's question.\\n\\nHere is the user's query: Explain how deep-sea life survives.\\n\"\n",
            "}\n",
            "------------------------------------------------------------\n",
            "model -> {\n",
            "  \"thought_signature\": \"CoIJAVSoXO7fBR_lSxtkrTPzNSYCxfZDP5VTvmZjXzFeZaYBWG2jVGLKvU0nkurOCUuBN4xh5HSf0Im3XE617RaHrHeT-_B8B7P4TCVgm9ur2hz9TiI48GMhAzc1TDUUHy2wq6znFCihVFNSXofh95kWR1mJSNnyF0U6Wfew07t98GuN_ZcpG7p4EoGKGIjQMR4KrH5E9gFWVXQO_811Y5zfcTnl1AIENT5PAsxQ4mYYOhxxdw7dsLZGnyPggFUgHHyKcBOXRJzNr4zCes19lDUeAiI_WgpYLag3SKCaEXnZyKBLMZeKzYbYgMDevArPTkBNqehohFdzDqirST53wCxcRXK2F-0bac05jPueTQLWlHzLJ5wpl-BOR--m2vs9VatKCkIdzes1Q-jmu7GSgdcmmGVfIygD20gjJlV1eTnY9_2X7d_ZTbIv1dlE3cjLps-j_P90AN4wj96HzZlng1yzsGbY4_c3tOeD9FQ4AB71OEeURVGUTi7Ke5GDrP1m5eaeTi2INX3iIr0Uij1uaX1BiBwBVMcWCfMkLrGZi4tsyt6ps-s6etEkem-T3zOx-D1xK_kynvQMFasdqXzw1Cp4O_A3Iv_PHAEoKM0dBdM24Mhe3xw4UDPV3uTwj5WaOKKg-qhRucrFwY_Xun6adSAj5S4X556vhsYvYE2hsv4_WaIofhljpxgfEZGtvSOjEOUj8zWhWZAOwGlGBY9pnORZeiiuYjLqOHu4y51JoNQjlrqgjG7UYVufncm8v7xNLQbT0pfM0saB97raFlxpBFt-HQPI8LRvsT-RVhMBMzw7mFtIymhO1kkzR7OPdZ7b8bTL5YXN4F2lVXVE3xJoJu7FqM_mA8BpQynZRCixo5BJ694peiC-4MLedSmnFV0DDMQBBCFP8L0ZKSva5WwOHgnb1nPVQq0CTYownNKyJ3Yov9OUx9kAufgrvyD68GYlVQZ1c8CHMbZipyCC-1x-_IegnI_kAIj_A0wCxcCHstmOjgzEoT5ileU-0k3Gcr88LOlA66SDSniuKTpUH8ykHs9M3g-hqSPH8HyL324kXxum5THowGlSNahPwI3ABBR0ci0-jf7LxugAMyP6gPHilSh4onJOpIMrt0BN_x_K7w_w866t-PZR72MzFY8A9nhNVqk4O4l7XGLOgA7L7cenrqq7YuGrRdGXNYuEljFbCz1ml7awcHxoZYD4oYUNweiL22Ifncqgzp-H1mJvBZd3nVE948KCS2eKMOAcvv_iBUZj8zdvscV5dd8SZhDW57E-DnY8fejGb9JWPYwf-4IC15O7S2NeNN9LCLHgyMTERpkSIbOiCcMu_UZbpz9Rp2J2x_Lk7VzggN-8s1vXLVeJHAsq5sPXkzUgJk4NBL0DIZJkm5Shj8wHBApuQhy_5Yks_ut79dB191hGaXEPGXoPH4MnGrj3WCx8VWRurFcc6Vxev-y2Xu-GDneQ2PacGoR8_I0Ej1PB6x7IPCQjXaq52ma4YTbfssh7EiVRyhwrv_WLAM_5YANiKZoOQ9nQFkmWwAggqcc=\",\n",
            "  \"function_call\": {\n",
            "    \"args\": {\n",
            "      \"search_queries\": [\n",
            "        \"Deep-sea life survival strategies\",\n",
            "        \"Adaptations of deep-sea organisms\",\n",
            "        \"How do deep-sea creatures survive extreme pressure?\",\n",
            "        \"Food sources in the deep sea\",\n",
            "        \"Chemosynthesis deep sea\",\n",
            "        \"Hydrothermal vents deep sea life\",\n",
            "        \"Marine snow deep sea\",\n",
            "        \"Bioluminescence deep sea life\",\n",
            "        \"Deep-sea fish adaptations\",\n",
            "        \"Deep-sea environment conditions\",\n",
            "        \"What do deep-sea animals eat?\",\n",
            "        \"Deep-sea extremophiles\"\n",
            "      ]\n",
            "    },\n",
            "    \"name\": \"wikipedia_search\"\n",
            "  }\n",
            "}\n",
            "------------------------------------------------------------\n",
            "user -> {\n",
            "  \"function_response\": {\n",
            "    \"name\": \"wikipedia_search\",\n",
            "    \"response\": {\n",
            "      \"result\": [\n",
            "        \"The provided text is about the video game \\\"Sea of Thieves\\\" and does not contain any information about deep-sea life survival strategies.\\n\\nBased on:\\n  https://en.wikipedia.org/wiki/Sea_of_Thieves\",\n",
            "        \"The provided source text focuses exclusively on \\\"Thalassophobia,\\\" which is the fear of deep bodies of water. It discusses the definition, causes, symptoms, diagnosis, and treatment of this phobia.\\n\\nThe text **does not contain any information** about \\\"Deep-sea life survival strategies.\\\" It only mentions \\\"aquatic animals\\\" and \\\"sea creatures\\\" in the context of things that people with thalassophobia might fear or that could trigger their fear.\\n\\nBased on:\\n  https://en.wikipedia.org/wiki/Thalassophobia\",\n",
            "        \"Based on the provided source, there is no information about \\\"Deep-sea life survival strategies.\\\" The text is a summary of the novel \\\"Whalefall\\\" and focuses on the plot, characters, and reception of the book, which involves a human character's survival inside a whale, not the survival strategies of deep-sea life.\\n\\nBased on:\\n  https://en.wikipedia.org/wiki/Whalefall_(novel)\",\n",
            "        \"The following information describes adaptations of deep-sea organisms:\\n\\n*   Deep-sea organisms rely heavily on marine snow as an energy source.\\n*   Deep-sea organisms have the same pressure within their bodies as is exerted on them from the outside, so they are not crushed by the extreme pressure.\\n*   Their high internal pressure results in the reduced fluidity of their membranes because molecules are squeezed together; organisms have adapted to this circumstance by increasing the proportion of unsaturated fatty acids in the lipids of the cell membranes.\\n*   Their metabolic processes must ultimately decrease the volume of the organism to some degree.\\n*   Deep-sea organisms contain gas-filled spaces (vacuoles), which means they can blow up if they come to the surface due to gas expansion.\\n*   Many deep-sea fish are blind and rely on their other senses, such as sensitivities to changes in local pressure and smell, to catch their food and avoid being caught.\\n*   Those that aren't blind have large and sensitive eyes that can use bioluminescent light, being as much as 100 times more sensitive to light than human eyes.\\n*   Some deep-sea fish have several Rhodopsin (Rh1) genes (e.g., silver spinyfin has 38), which may help them see in the depths of the ocean.\\n*   Many species are dark to blend in with their environment and avoid predation.\\n*   Many deep-sea fish are bioluminescent, with extremely large eyes adapted to the dark.\\n*   Bioluminescence is used to search for food and attract prey (e.g., anglerfish), claim territory through patrol, communicate and find a mate, and distract or temporarily blind predators to escape.\\n*   Some organisms camouflage themselves from predators below them by illuminating their bellies (counter-illumination) to match the colour and intensity of light from above so that no shadow is cast in the mesopelagic zone.\\n*   Deep-sea fishes usually do not have swim bladders because of the high pressure of their environment.\\n*   Instead, they exhibit structures similar to hydrofoils in order to provide hydrodynamic lift.\\n*   The deeper a fish lives, the more jelly-like its flesh and the more minimal its bone structure.\\n*   They reduce their tissue density through high fat content, reduction of skeletal weight (through reductions of size, thickness and mineral content), and water accumulation.\\n*   The body shapes of deep-sea fish are generally better adapted for periodic bursts of swimming rather than constant swimming.\\n*   Some have long feelers to help them locate prey or attract mates in the pitch black of the deep ocean.\\n*   The deep-sea angler fish has a long fishing-rod-like adaptation protruding from its face, on the end of which is a bioluminescent piece of skin that wriggles like a worm to lure its prey.\\n*   To consume other fish that are the same size or larger, they have great sharp teeth, hinged jaws, disproportionately large mouths, and expandable bodies (e.g., gulper eel).\\n*   Ray finned species with spiny fins are rare, suggesting deep-sea fish are ancient and well adapted, making invasions by more modern fishes unsuccessful.\\n*   Most mesopelagic fish make daily vertical migrations, moving at night into the epipelagic zone to feed and returning to the depths for safety during the day, often following zooplankton.\\n*   Vertical migrations are undertaken with the assistance of a swim bladder, which is inflated to move up and deflated to return to depths, adjusting to pressure changes.\\n*   Some mesopelagic fishes make daily migrations through the thermocline, displaying considerable tolerances for temperature change.\\n*   Mesopelagic fish have muscular bodies, ossified bones, scales, well developed gills and central nervous systems, and large hearts and kidneys.\\n*   Mesopelagic plankton feeders have small mouths with fine gill rakers, while piscivores have larger mouths and coarser gill rakers.\\n*   Most mesopelagic fish are visual predators with large eyes.\\n*   Some deeper water fish have tubular eyes with big lenses and only rod cells that look upwards, providing binocular vision and great sensitivity to small light signals, allowing them to pick out prey silhouetted against the gloom above.\\n*   Mesopelagic fish usually lack defensive spines, and use colour to camouflage themselves: ambush predators are dark, black or red (red functions as black due to light absorption).\\n*   Migratory forms use countershaded silvery colours.\\n*   On their bellies, they often display photophores producing low grade light for counter-illumination.\\n*   Some predators have yellow lenses that filter ambient light, leaving bioluminescence visible.\\n*   The brownsnout spookfish employs a mirror, not a lens, to focus an image in its eyes.\\n*   Bathypelagic fish have slow metabolisms and unspecialized diets, preferring to sit and wait for food.\\n*   Their bodies are elongated with weak, watery muscles and skeletal structures, allowing them to not be compressed by great pressures.\\n*   They often have extensible, hinged jaws with recurved teeth.\\n*   They are slimy, without scales.\\n*   The central nervous system is confined to the lateral line and olfactory systems; eyes are small and may not function; gills, kidneys, hearts, and swim bladders are small or missing. These features (acquired through neoteny) allow them to remain suspended in water with little energy expenditure.\\n*   The swim bladders of bathypelagic fish are either absent or scarcely operational, and they do not normally undertake vertical migrations.\\n*   Some deep-sea fishes have swim bladders that function when young in the upper epipelagic zone, but they wither or fill with fat as the fish move to adult habitat.\\n*   Cusk-eel and rough abyssal grenadier, found at great depths, still have functional swim bladders, allowing them to maintain high bone density and strong jaws.\\n*   Their most important sensory systems are usually the inner ear (responds to sound) and the lateral line (responds to changes in water pressure); the olfactory system can also be important for males finding females by smell.\\n*   Bathypelagic fish are black, or sometimes red, with few photophores, used to entice prey or attract a mate.\\n*   They are not selective in feeding, grabbing whatever comes close, accomplished by having a large mouth with sharp teeth for grabbing large prey and overlapping gill rakers to prevent small prey from escaping.\\n*   For finding a mate, some species depend on bioluminescence with unique patterns; others are hermaphrodites.\\n*   Female anglerfish release pheromones to attract tiny males; when a male finds her, he bites on to her and never lets go, fusing their circulatory systems and atrophying into gonads, ensuring a mate is immediately available for spawning.\\n*   Deep-sea organisms possess adaptations at cellular and physiological levels to survive in environments of great pressure.\\n*   Species have evolved changes in their protein structure and reaction criteria to withstand pressure.\\n*   Deep-sea cellular membranes favor phospholipid bilayers with a higher proportion of unsaturated fatty acids, inducing higher fluidity.\\n*   Deep-sea species exhibit lower changes of entropy and enthalpy.\\n*   Globular proteins of deep-sea fish (e.g., G-actin) are relatively rigid compared to surface fish.\\n*   Proteins in deep-sea fish are structurally strengthened by modification of bonds in the tertiary structure, which also induces high levels of thermal stability.\\n*   Na+/K+ -ATPases of deep-sea fishes exhibit a much higher tolerance of hydrostatic pressure compared to shallow-water counterparts, due to adaptations in the protein and lipid moieties.\\n*   Ten orders, thirteen families and about 200 known species of deep-sea fish have evolved a gelatinous layer below the skin or around the spine, used for buoyancy, low-cost growth and to increase swimming efficiency by reducing drag.\\n\\nBased on:\\n  https://en.wikipedia.org/wiki/Deep-sea_fish\",\n",
            "        \"Organisms living within the deep sea have a variety of adaptations to survive in these conditions.\\nOrganisms can survive in the deep sea through a number of feeding methods including scavenging, predation and filtration, with a number of organisms surviving by feeding on marine snow.\\nInstead of relying on gas for their buoyancy, many deep-sea species have jelly-like flesh consisting mostly of glycosaminoglycans, which provides them with very low density.\\nIt is also common among deep water squid to combine the gelatinous tissue with a flotation chamber filled with a coelomic fluid made up of the metabolic waste product ammonium chloride, which is lighter than the surrounding water.\\nThe midwater fish have special adaptations to cope with these conditions\\u2014they are small, usually being under 25 centimetres (10 in); they have slow metabolisms and unspecialized diets, preferring to sit and wait for food rather than waste energy searching for it.\\nThey have elongated bodies with weak, watery muscles and skeletal structures.\\nThey often have extendable, hinged jaws with recurved teeth.\\nBecause of the sparse distribution and lack of light, finding a partner with which to breed is difficult, and many organisms are hermaphroditic.\\nBecause light is so scarce, fish often have larger than normal, tubular eyes with only rod cells.\\nTheir upward field of vision allows them to seek out the silhouette of possible prey.\\nPrey fish however also have adaptations to cope with predation. These adaptations are mainly concerned with reduction of silhouettes, a form of camouflage.\\nThe two main methods by which this is achieved are reduction in the area of their shadow by lateral compression of the body, and counter illumination via bioluminescence.\\nThis is achieved by production of light from ventral photophores, which tend to produce such light intensity to render the underside of the fish of similar appearance to the background light.\\nFor more sensitive vision in low light, some fish have a retroreflector behind the retina.\\nFlashlight fish have this plus photophores, which combination they use to detect eyeshine in other fish.\\nThere are many scavengers that feed primarily or entirely upon large food falls.\\nThere are a number of filter feeders that feed upon organic particles using tentacles, such as Freyella elegans.\\nOne example is the symbiotic relationship between the tube worm Riftia and chemosynthetic bacteria.\\nDeep-sea fish have different adaptations in their proteins, anatomical structures, and metabolic systems to survive in the Deep sea, where the inhabitants have to withstand great amount of hydrostatic pressure.\\nDeep sea species must undergo physiological and structural adaptations to preserve protein functionality against pressure.\\nSome Deep-sea fish developed pressure tolerance through the change in mechanism of their \\u03b1-actin.\\nIn some species that live in depths greater than 5 km (3.1 mi), C.armatus and C.yaquinae have specific substitutions on the active sites of \\u03b1-Actin, which serves as the main component of muscle fiber.\\nThese specific substitutions, Q137K and V54A from C.armatus or I67P from C.yaquinae are predicted to have importance in pressure tolerance.\\nSubstitution in the active sites of actin result in significant changes in the salt bridge patterns of the protein, which allows for better stabilization in ATP binding and sub unit arrangement.\\nIt was found that deep sea fish have more salt bridges in their actins compared to fish inhabiting the upper zones of the sea.\\nFor certain chondrichthyans, it was found that Trimethylamine N-oxide (TMAO) increased with depth, replacing other osmolytes and urea.\\nDue to the ability of TMAO being able to protect proteins from high hydrostatic pressure destabilizing proteins, the osmolyte adjustment serves are an important adaptation for deep sea fish to withstand high hydrostatic pressure.\\nDeep-sea organisms possess molecular adaptations to survive and thrive in the deep oceans.\\nMariana hadal snailfish developed modification in the Osteocalcin(burlap) gene, where premature termination of the gene was found.\\nThe frameshift mutation seems to have resulted in the open skull and cartilage-based bone formation in Mariana hadal snailfish.\\n\\nBased on:\\n  https://en.wikipedia.org/wiki/Deep_sea\",\n",
            "        \"Adaptations of deep-sea organisms mentioned in the source include:\\n\\n*   **Deep-sea gigantism:** The tendency for species of deep-sea dwelling animals to be larger than their shallower-water relatives. This is considered a necessary adaptation to colder temperature, food scarcity, reduced predation pressure, and increased dissolved oxygen concentrations.\\n*   **Response to lower temperature:** Decreasing temperature is thought to result in increased cell size and increased life span (associated with delayed sexual maturity), both leading to an increase in maximum body size. Continued growth throughout life is characteristic of crustaceans in this environment.\\n*   **Response to food scarcity:** Larger body size can improve ability to forage for widely scattered resources. Larger offspring, with greater initial stored food reserves, can drift for greater distances. Giant isopods gorge on food when available, distending their bodies, and can also survive 5 years without food in captivity. A larger animal's metabolism becomes more efficient, which provides benefit under conditions of limited food supply.\\n*   **Response to reduced predation pressure:** Reduced predation pressure in deeper waters is a possible influence on adaptations.\\n*   **Response to increased dissolved oxygen:** Deep-sea gigantism could be an adaptive trait to combat asphyxiation in frigid, dense ocean waters. Larger organisms are able to intake more dissolved oxygen within the ocean, allowing for sufficient respiration.\\n\\nBased on:\\n  https://en.wikipedia.org/wiki/Deep-sea_gigantism\",\n",
            "        \"From the \\\"Hyperbaricity\\\" section:\\n*   \\\"These animals have evolved to survive the extreme pressure of the sub-photic zones.\\\"\\n*   \\\"To cope with the pressure, many fish are rather small, usually not exceeding 25 cm in length.\\\"\\n*   \\\"Scientists have discovered that the deeper these creatures live, the more gelatinous their flesh and more minimal their skeletal structure.\\\"\\n*   \\\"These creatures have also eliminated all excess cavities that would collapse under the pressure, such as swim bladders.\\\"\\n\\nFrom the \\\"Bathyal\\\" section:\\n*   \\\"The fish that do live there [bathyal zone] may have reduced or completely lost their gills, kidneys, hearts, and swimbladders, have slimy instead of scaly skin, and have a weak skeletal and muscular build.\\\"\\n*   \\\"This lack of ossification is an adaptation to save energy when food is scarce.\\\"\\n\\nBased on:\\n  https://en.wikipedia.org/wiki/Deep-sea_community\",\n",
            "        \"Here's the extracted information about \\\"Chemosynthesis deep sea\\\":\\n\\n*   Relative to the majority of the deep sea, the areas around hydrothermal vents are biologically more productive, often hosting complex communities fueled by the chemicals dissolved in the vent fluids.\\n*   Chemosynthetic bacteria and archaea found around hydrothermal vents form the base of the food chain, supporting diverse organisms including giant tube worms, clams, limpets, and shrimp.\\n*   Life has traditionally been seen as driven by energy from the sun, but deep-sea organisms have no access to sunlight, so biological communities around hydrothermal vents must depend on nutrients found in the dusty chemical deposits and hydrothermal fluids in which they live.\\n*   Previously, benthic oceanographers assumed that vent organisms were dependent on marine snow, as deep-sea organisms are.\\n*   Some hydrothermal vent organisms do consume this \\\"rain\\\", but with only such a system, life forms would be sparse.\\n*   Compared to the surrounding sea floor, however, hydrothermal vent zones have a density of organisms 10,000 to 100,000 times greater.\\n*   The hydrothermal vents are recognized as a type of chemosynthetic based ecosystems (CBE) where primary productivity is fuelled by chemical compounds as energy sources instead of light (chemoautotrophy).\\n*   Hydrothermal vent communities are able to sustain such vast amounts of life because vent organisms depend on chemosynthetic bacteria for food.\\n*   The water from the hydrothermal vent is rich in dissolved minerals and supports a large population of chemoautotrophic bacteria.\\n*   These bacteria use sulfur compounds, particularly hydrogen sulfide, a chemical highly toxic to most known organisms, to produce organic material through the process of chemosynthesis.\\n*   The ecosystem so formed is reliant upon the continued existence of the hydrothermal vent field as the primary source of energy, which differs from most surface life on Earth, which is based on solar energy.\\n*   However, although it is often said that these communities exist independently of the sun, some of the organisms are actually dependent upon oxygen produced by photosynthetic organisms, while others are anaerobic.\\n*   The chemosynthetic bacteria grow into a thick mat which attracts other organisms, such as amphipods and copepods, which graze upon the bacteria directly.\\n*   Larger organisms, such as snails, shrimp, crabs, tube worms, fish (especially eelpout, cutthroat eel, Ophidiiformes and Symphurus thermophilus), and octopuses (notably Vulcanoctopus hydrothermalis), form a food chain of predator and prey relationships above the primary consumers.\\n*   Sunlight is nonexistent, so many organisms, such as archaea and extremophiles, convert the heat, methane, and sulfur compounds provided by black smokers into energy through a process called chemosynthesis.\\n*   More complex life forms, such as clams and tubeworms, feed on these organisms.\\n*   The organisms at the base of the food chain also deposit minerals into the base of the black smoker, therefore completing the life cycle.\\n*   Hydrothermal vent ecosystems have enormous biomass and productivity, but this rests on the symbiotic relationships that have evolved at vents.\\n*   Deep-sea hydrothermal vent ecosystems differ from their shallow-water and terrestrial hydrothermal counterparts due to the symbiosis that occurs between macroinvertebrate hosts and chemoautotrophic microbial symbionts in the former.\\n*   Since sunlight does not reach deep-sea hydrothermal vents, organisms in deep-sea hydrothermal vents cannot obtain energy from the sun to perform photosynthesis.\\n*   Instead, the microbial life found at hydrothermal vents is chemosynthetic; they fix carbon by using energy from chemicals such as sulfide, as opposed to light energy from the sun.\\n*   In other words, the symbiont converts inorganic molecules (H2S, CO2, O) to organic molecules that the host then uses as nutrition.\\n*   What was discovered was the ubiquitous symbiosis of chemoautotrophs living in (endosymbiosis) the vent animals' gills; the reason why multicellular life is capable to survive the toxicity of vent systems.\\n*   In the early stages of studying life at hydrothermal vents, there were differing theories regarding the mechanisms by which multicellular organisms were able to acquire nutrients from these environments, and how they were able to survive in such extreme conditions.\\n*   In 1977, it was hypothesized that the chemoautotrophic bacteria at hydrothermal vents might be responsible for contributing to the diet of suspension-feeding bivalves.\\n*   Finally, in 1981, it was understood that giant tubeworm nutrition acquisition occurred as a result of chemoautotrophic bacterial endosymbionts.\\n*   As scientists continued to study life at hydrothermal vents, it was understood that symbiotic relationships between chemoautotrophs and macrofauna invertebrate species was ubiquitous.\\n*   For instance, in 1983, clam gill tissue was confirmed to contain bacterial endosymbionts; in 1984 vent bathymodiolid mussels and vesicomyid clams were also found to carry endosymbionts.\\n*   Tubeworms have no mouth and no gut, but they do have a \\\"trophosome\\\", which is where they deal with nutrition and where their endosymbionts are found.\\n*   They also have a bright red plume, which they use to uptake compounds such as O, H2S, and CO2, which feed the endosymbionts in their trophosome.\\n*   In 1988, research confirmed thiotrophic (sulfide-oxidizing) bacteria in Alviniconcha hessleri, a large vent mollusk.\\n*   Furthermore, while some symbionts reduce sulfur compounds, others are known as \\\"methanotrophs\\\" and reduce carbon compounds, namely methane.\\n*   While chemosynthesis occurring at the deep ocean allows organisms to live without sunlight in the immediate sense, they technically still rely on the sun for survival, since oxygen in the ocean is a byproduct of photosynthesis.\\n*   However, if the sun were to suddenly disappear and photosynthesis ceased to occur on our planet, life at the deep-sea hydrothermal vents could continue for millennia (until the oxygen was depleted).\\n*   Chemosynthetic ecosystems surrounding the Gal\\u00e1pagos Rift submarine hydrothermal vents were first directly observed in 1977.\\n*   Conservation of hydrothermal vent ecosystems after the fact of mining of an active system would depend on the recolonization of chemosynthetic bacteria, and therefore the continuation of the hydrothermal vent fluid as it is the main hydrothermal energy source.\\n*   Hydrogen sulfide chemosynthesis - system of generating energy used in hydrothermal vents (from \\\"See also\\\" section).\\n\\nBased on:\\n  https://en.wikipedia.org/wiki/Hydrothermal_vent\",\n",
            "        \"Here is the relevant information about marine snow in the deep sea:\\n\\n*   In the deep ocean, marine snow is a continuous shower of mostly organic detritus falling from the upper layers of the water column.\\n*   It is a significant means of exporting energy from the light-rich photic zone to the aphotic zone below, which is referred to as the biological pump.\\n*   Export production is the amount of organic matter produced in the ocean by primary production that is not recycled (remineralised) before it sinks into the aphotic zone.\\n*   Marine snow can be an important food source for organisms living in the aphotic zone, particularly for organisms that live very deep in the water column.\\n*   Most organic components of marine snow are consumed by microbes, zooplankton and other filter-feeding animals within the first 1,000 metres of their journey.\\n*   Marine snow may be considered the foundation of deep-sea mesopelagic and benthic ecosystems: As sunlight cannot reach them, deep-sea organisms rely heavily on marine snow as an energy source.\\n*   The small percentage of material not consumed in shallower waters becomes incorporated into the muddy \\\"ooze\\\" blanketing the ocean floor, where it is further decomposed through biological activity.\\n*   As the aggregates slowly sink to the bottom of the ocean, the many microorganisms residing on them are constantly respiring and contribute greatly to the microbial loop.\\n*   Aggregates that sink more quickly to the bottom of the ocean have a greater chance of exporting carbon to the deep sea floor.\\n*   Carbon export to the deep ocean in regions with high dust deposition is strongly controlled by dust input to the surface ocean while suspended dust particles in deeper water layers do not significantly interact with sinking aggregates.\\n*   The particulate organic carbon formed in the euphotic zone is processed by marine microorganisms (microbes), zooplankton and their consumers into organic aggregates (marine snow), which is then exported to the mesopelagic (200\\u20131000 m depth) and bathypelagic zones by sinking and vertical migration by zooplankton and fish.\\n*   Sequestration flux is the sedimentation out of the mesopelagic zone (at approximately 1000 m depth).\\n*   A portion of the particulate organic carbon is respired back to CO2 in the oceanic water column at depth, mostly by heterotrophic microbes and zooplankton, thus maintaining a vertical gradient in concentration of dissolved inorganic carbon (DIC).\\n*   This deep-ocean DIC returns to the atmosphere on millennial timescales through thermohaline circulation.\\n*   Only about 1% of the surface production reaches the sea floor.\\n*   Marine snow aggregates collected from the bathypelagic zone were found to consist largely of fungi and labyrinthulomycetes.\\n*   Smaller aggregates do not harbor as many eukaryotic organisms which is similar to what is found in the deep ocean.\\n*   The bathypelagic aggregates mostly resembled those found in the surface ocean.\\n*   It implies higher rates of remineralization in the bathypelagic zone.\\n*   Remineralization occurs typically below 200 m depth.\\n*   The dark ocean harbors around 65% of all pelagic Bacteria and Archaea.\\n*   The deep ocean harbors more than 98% of the dissolved inorganic carbon pool, along with a rapid sedimentation rate that results in low particulate organic carbon inputs.\\n*   There is a mismatch from the microbial carbon demand in the deep ocean and the carbon export from the surface ocean.\\n*   Because of the relatively long residence time of the ocean's thermohaline circulation, carbon transported as marine snow into the deep ocean by the biological pump can remain out of contact with the atmosphere for more than 1000 years.\\n*   When the marine snow is finally decomposed to inorganic nutrients and dissolved carbon dioxide, these are effectively isolated from the surface ocean for relatively long time scales related to ocean circulation.\\n*   Enhancing the quantity of marine snow that reaches the deep ocean is the basis of several geoengineering schemes to enhance carbon sequestration by the ocean.\\n*   Increases in ocean temperatures may result in a decrease in the production of marine snow due to the enhanced stratification of the water column.\\n*   Recent research indicates transported bacteria may exchange genes with previously thought to be isolated populations of bacteria inhabiting the breadth of the ocean floor.\\n*   In such an immense area there may be as yet undiscovered species tolerant of high pressures and extreme cold, perhaps finding use in bioengineering and pharmacy.\\n\\nBased on:\\n  https://en.wikipedia.org/wiki/Marine_snow\",\n",
            "        \"The programme then introduces many luminous deep sea animals, including the vampire squid, the polychaete worm Tomopteris that generates yellow light, the jellyfish Atolla, the comb jelly Beroe, the viper fish, pyrosomes, a dragonfish, and the polychaete worm Flota. Next, the programme discusses specialised adaptations in the eyes of particular animals to see bioluminescence, such as the barreleye fish and the cock-eyed squid.\\n\\nBased on:\\n  https://en.wikipedia.org/wiki/Life_That_Glows\",\n",
            "        \"Sea urchins inhabit depth zones from the intertidal zone to deep seas of 5,000 m (16,000 ft), and even to hadal zone depths (6850 metres).\\n\\nSea urchins feed primarily on algae, but also eat slow-moving or sessile animals such as crinoids and sponges. They are primarily herbivores but can feed on sea cucumbers and a wide range of invertebrates, such as mussels, polychaetes, sponges, brittle stars, and crinoids, making them omnivores, consumers at a range of trophic levels.\\n\\nBased on:\\n  https://en.wikipedia.org/wiki/Sea_urchin\",\n",
            "        \"Here's the relevant information about deep-sea extremophiles from the provided source:\\n\\n*   Much of the fluid trapped in sediments of the subducting slab returns to the surface at the oceanic trench, producing mud volcanoes and cold seeps. These support unique biomes based on chemotrophic microorganisms.\\n*   The fluids released at mud volcanoes and cold seeps are rich in methane and hydrogen sulfide, providing chemical energy for chemotrophic microorganisms that form the base of a unique trench biome.\\n*   Cold seep communities have been identified in the inner trench slopes of the western Pacific (especially Japan), South America, Barbados, the Mediterranean, Makran, and the Sunda trench. These are found at depths as great as 6,000 meters (20,000 ft).\\n*   The genome of the extremophile Deinococcus from Challenger Deep has sequenced for its ecological insights and potential industrial uses.\\n*   Because trenches are the lowest points in the ocean floor, there is concern that plastic debris may accumulate in trenches and endanger the fragile trench biomes.\\n\\nBased on:\\n  https://en.wikipedia.org/wiki/Oceanic_trench\"\n",
            "      ]\n",
            "    }\n",
            "  }\n",
            "}\n",
            "------------------------------------------------------------\n",
            "model -> {\n",
            "  \"thought_signature\": \"CpQwAVSoXO6mZ72FvYSu-DZp-MR28zWVKDqT5anfFFdWVXZ-xV5-aUFsiF3_XCyRqK0r52pPzvHpoERv2QC1HDl5klmGJ2JKkdmqvK0vsFrH6O7ps1FAVkh5o9PBVGggpzJj4mN2z2GUF0XhZUTKBKiz0Ko9Lryo7FzCSlhS6gbBI7_ZxgdMRx32GqLapNj132ImizDccZiwjoPwTrADsUNqFrL5NllaEfPpBkghLVOcTN5nBA_txIhOYSlgRDJUpihhUsXe4LOWcR6x16YvIOLE36FK6hLW1ho-xWLqtRkGSYEE-jfTo5PNh8TEVVjnSb3KRN5jH714J5GBhgy376jRx4xX_mRb5llKIW2ynvd27E0RTHYo8n8I_aPOh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dA79sW5BRIRPc9cxoRWKKZEy-M6BdYbM1I3V0q4ap8EfUjXOFUjsPU-clYTXuCszmMX0V2p-ug_z8ZrJvM2SVh9pxEfZrwGknKuGq7TbkBYI1R-CfyZhBdj6uQPlaGDwPgJLfwWD1mRPbA4XDbTz9AbvpOW9TzSxqi6wskXntz5QAp_edJfnfwLDXmQkJtt8PfNDZ228Lk7ldqlZq-OJTQcOy7dUVp2CZf_7RRChhT0JcOUIA1r64AuZe3nqq1cyA=\",\n",
            "  \"text\": \"Deep-sea life has evolved remarkable adaptations to survive the harsh conditions of its environment, characterized by immense pressure, perpetual darkness, extremely cold temperatures, and scarce food resources.\\n\\nHere's how deep-sea organisms manage to thrive:\\n\\n1.  **Pressure Adaptations:**\\n    *   **Internal Pressure Equalization:** Deep-sea creatures maintain an internal body pressure that is equal to the external hydrostatic pressure, preventing them from being crushed.\\n    *   **Flexible Bodies:** Many species have gelatinous, watery flesh with minimal bone structure and reduced tissue density. This allows their bodies to compress without damage.\\n    *   **Absence of Gas-Filled Spaces:** Most deep-sea fish lack swim bladders (gas-filled organs used for buoyancy in shallower waters) as these would collapse under pressure. Instead, some use lipid-rich tissues or have hydrofoil-like fins for lift.\\n    *   **Molecular Adaptations:** At a cellular level, their proteins and enzymes are specially adapted to function under high pressure, often being more rigid or having modified structures (e.g., increased salt bridges in actin, higher proportion of unsaturated fatty acids in cell membranes to maintain fluidity). Some use osmolytes like Trimethylamine N-oxide (TMAO) to protect proteins.\\n\\n2.  **Food Acquisition:**\\n    *   **Marine Snow:** In the vast majority of the deep sea, the primary food source is \\\"marine snow\\\"\\u2014a continuous shower of organic detritus (dead organisms, fecal pellets, etc.) falling from the productive upper layers of the ocean. Organisms filter this snow or scavenge larger food falls.\\n    *   **Chemosynthesis:** Around hydrothermal vents and cold seeps, life thrives independently of sunlight through chemosynthesis. Specialized bacteria and archaea convert chemical compounds (like hydrogen sulfide and methane) from the Earth's interior into organic matter. These microorganisms form the base of the food web, supporting dense communities of unique organisms, often through symbiotic relationships (e.g., tube worms hosting chemosynthetic bacteria).\\n    *   **Efficient Feeding:** Due to food scarcity, many deep-sea fish have slow metabolisms and unspecialized diets, preferring to \\\"sit and wait\\\" for prey. They often possess large, hinged, and extensible jaws with sharp, recurved teeth to engulf prey of their own size or larger.\\n\\n3.  **Light and Sensory Adaptations:**\\n    *   **Bioluminescence:** In the absence of sunlight, many deep-sea creatures produce their own light through bioluminescence. This is used for various purposes: attracting prey (like the anglerfish's glowing lure), finding mates, deterring predators (e.g., by startling or counter-illuminating their undersides to blend with faint overhead light), and communication.\\n    *   **Enhanced Vision:** While some deep-sea fish are blind, others have exceptionally large, tubular eyes with highly sensitive rod cells that are adapted to detect the faintest flickers of bioluminescence or silhouettes against the dim light from above.\\n    *   **Other Senses:** Given the limited utility of sight, deep-sea organisms heavily rely on other senses. They possess highly developed lateral line systems to detect changes in water pressure and vibrations, an acute sense of smell (olfactory system) to locate food or mates, and sensitive inner ears. Many also have long feelers or tentacles to navigate and find prey in the darkness.\\n\\n4.  **Metabolic and Physical Adaptations:**\\n    *   **Slow Metabolism:** To conserve energy in a food-scarce environment, deep-sea organisms generally have very slow metabolisms and often grow slowly and live long lives.\\n    *   **Body Shape and Movement:** Their bodies are often elongated with weak, watery muscles and minimal skeletal structures, which allows them to remain suspended in water with little energy expenditure. Their body shapes are generally better suited for periodic bursts of swimming rather than continuous movement.\\n    *   **Deep-Sea Gigantism:** Some deep-sea species exhibit gigantism, growing much larger than their shallow-water relatives. This is thought to be an adaptation to colder temperatures, food scarcity (larger size improves foraging ability and metabolic efficiency), and reduced predation pressure.\\n\\n5.  **Reproduction:**\\n    *   Finding a mate in the vast, dark deep sea can be challenging. Adaptations include hermaphroditism (being both male and female) or unique reproductive strategies, such as the parasitic male anglerfish, which permanently attaches to the female, ensuring a mate is always available.\"\n",
            "}\n",
            "------------------------------------------------------------\n"
          ]
        }
      ],
      "source": [
        "for content in chat._comprehensive_history:\n",
        "  part = content.parts[0]\n",
        "\n",
        "  print(f'{content.role} -> ', end='')\n",
        "  print(json.dumps(part.to_json_dict(), indent=2))\n",
        "  print('---' * 20)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "WDWc9Fj9Ig6A"
      },
      "source": [
        "In the chat history you can see all 4 steps:\n",
        "\n",
        "1. The user sent the query.\n",
        "2. The model replied with a `genai.protos.FunctionCall` calling the `wikipedia_search` with a number of relevant searches.\n",
        "3. Because you set `enable_automatic_function_calling=True` when creating the `genai.ChatSession`, it  executed the search function and returned the list of article summaries to the model.\n",
        "4. Folliwing the instructions in the prompt, the model generated a final answer based on those summaries.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "PJP1EAgfnPUA"
      },
      "source": [
        "## [Optional] Manually execute the function call"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Sa5ke2ssKl7M"
      },
      "source": [
        "If you want to understand what happened behind the scenes, this section executes the `FunctionCall` manually to demonstrate."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 29,
      "metadata": {
        "id": "wavbHrL3K5vo"
      },
      "outputs": [],
      "source": [
        "chat = client.chats.create(\n",
        "    model=MODEL_ID,\n",
        "    config=config\n",
        ")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 30,
      "metadata": {
        "id": "ON4LTcmiLs2E"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Searching for \"How do deep-sea creatures adapt to high pressure?\"\n",
            "Related search terms: ['Deep sea', 'Deep-sea fish', 'Oceanic zone']\n",
            "Fetching page: \"Deep sea\"\n",
            "Information Source: https://en.wikipedia.org/wiki/Deep_sea\n",
            "Fetching page: \"Deep-sea fish\"\n",
            "Information Source: https://en.wikipedia.org/wiki/Deep-sea_fish\n",
            "Fetching page: \"Oceanic zone\"\n",
            "Information Source: https://en.wikipedia.org/wiki/Oceanic_zone\n",
            "Searching for \"What are the food sources for deep-sea life?\"\n",
            "Related search terms: ['Deep-sea fish', 'Deep-sea wood', 'Deep sea']\n",
            "Fetching page: \"Deep-sea wood\"\n",
            "Information Source: https://en.wikipedia.org/wiki/Deep-sea_wood\n",
            "Searching for \"How do deep-sea organisms survive in the absence of sunlight?\"\n",
            "Related search terms: ['Deep-sea community', 'Hydrothermal vent', 'Abyssal zone']\n",
            "Fetching page: \"Deep-sea community\"\n",
            "Information Source: https://en.wikipedia.org/wiki/Deep-sea_community\n",
            "Fetching page: \"Hydrothermal vent\"\n",
            "Information Source: https://en.wikipedia.org/wiki/Hydrothermal_vent\n",
            "Fetching page: \"Abyssal zone\"\n",
            "Information Source: https://en.wikipedia.org/wiki/Abyssal_zone\n",
            "Searching for \"What are the unique adaptations of deep-sea animals?\"\n",
            "Related search terms: ['Deep sea', 'Deep-sea community', 'Deep-sea fish']\n",
            "Searching for \"Deep-sea hydrothermal vents and life\"\n",
            "Related search terms: ['Hydrothermal vent', 'Deep-sea community', 'Hydrothermal vent microbial communities']\n",
            "Fetching page: \"Hydrothermal vent microbial communities\"\n",
            "Information Source: https://en.wikipedia.org/wiki/Hydrothermal_vent_microbial_communities\n",
            "Searching for \"Deep-sea chemosynthesis\"\n",
            "Related search terms: ['Deep-sea community', 'Deep sea', 'Hydrothermal vent']\n",
            "Searching for \"Bioluminescence in deep-sea creatures\"\n",
            "Related search terms: ['Deep-sea community', 'Deep sea', 'Deep-sea fish']\n",
            "Searching for \"Deep-sea extremophiles survival mechanisms\"\n",
            "Related search terms: ['Hydrothermal vent', 'Extremophile', 'Deep-sea community']\n",
            "Fetching page: \"Extremophile\"\n",
            "Information Source: https://en.wikipedia.org/wiki/Extremophile\n",
            "Searching for \"How do deep-sea fish regulate buoyancy?\"\n",
            "Related search terms: ['Deep sea', 'Deep sea mining', 'Neutral buoyancy']\n",
            "Fetching page: \"Deep sea mining\"\n",
            "Information Source: https://en.wikipedia.org/wiki/Deep_sea_mining\n",
            "Fetching page: \"Neutral buoyancy\"\n",
            "Information Source: https://en.wikipedia.org/wiki/Neutral_buoyancy\n",
            "Searching for \"What is marine snow and its role in deep-sea ecosystems?\"\n",
            "Related search terms: ['Deep-sea community', 'Deep-sea fish', 'Deep sea']\n",
            "Information Sources:\n",
            "     https://en.wikipedia.org/wiki/Deep_sea\n",
            "     https://en.wikipedia.org/wiki/Deep-sea_fish\n",
            "     https://en.wikipedia.org/wiki/Oceanic_zone\n",
            "     https://en.wikipedia.org/wiki/Deep-sea_wood\n",
            "     https://en.wikipedia.org/wiki/Deep-sea_community\n",
            "     https://en.wikipedia.org/wiki/Hydrothermal_vent\n",
            "     https://en.wikipedia.org/wiki/Abyssal_zone\n",
            "     https://en.wikipedia.org/wiki/Hydrothermal_vent_microbial_communities\n",
            "     https://en.wikipedia.org/wiki/Extremophile\n",
            "     https://en.wikipedia.org/wiki/Deep_sea_mining\n",
            "     https://en.wikipedia.org/wiki/Neutral_buoyancy\n"
          ]
        }
      ],
      "source": [
        "result = chat.send_message(instructions.format(query=query))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "__JN3YuHe7fR"
      },
      "source": [
        "Initially the model returns a FunctionCall:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 59,
      "metadata": {
        "id": "Lgngdvcdi06F"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "{\n",
            "  \"args\": {\n",
            "    \"search_queries\": [\n",
            "      \"How do deep-sea creatures adapt to high pressure?\",\n",
            "      \"What are the food sources for deep-sea life?\",\n",
            "      \"How do deep-sea organisms survive in the absence of sunlight?\",\n",
            "      \"What are the unique adaptations of deep-sea animals?\",\n",
            "      \"Deep-sea hydrothermal vents and life\",\n",
            "      \"Deep-sea chemosynthesis\",\n",
            "      \"Bioluminescence in deep-sea creatures\",\n",
            "      \"Deep-sea extremophiles survival mechanisms\",\n",
            "      \"How do deep-sea fish regulate buoyancy?\",\n",
            "      \"What is marine snow and its role in deep-sea ecosystems?\"\n",
            "    ]\n",
            "  },\n",
            "  \"name\": \"wikipedia_search\"\n",
            "}\n"
          ]
        }
      ],
      "source": [
        "fc = result.automatic_function_calling_history[1].parts[0].function_call\n",
        "fc = fc.to_json_dict()\n",
        "print(json.dumps(fc, indent=2))\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 62,
      "metadata": {
        "id": "Bfp1Kqv7PE8N"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "'wikipedia_search'"
            ]
          },
          "execution_count": 62,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "fc['name']"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "xpD3axtDmfZb"
      },
      "source": [
        "Call the function with generated arguments to get the results."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 63,
      "metadata": {
        "id": "Ek4g-CTAPSou"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Searching for \"How do deep-sea creatures adapt to high pressure?\"\n",
            "Related search terms: ['Deep sea', 'Deep-sea fish', 'Oceanic zone']\n",
            "Fetching page: \"Deep sea\"\n",
            "Information Source: https://en.wikipedia.org/wiki/Deep_sea\n",
            "Fetching page: \"Deep-sea fish\"\n",
            "Information Source: https://en.wikipedia.org/wiki/Deep-sea_fish\n",
            "Fetching page: \"Oceanic zone\"\n",
            "Information Source: https://en.wikipedia.org/wiki/Oceanic_zone\n",
            "Searching for \"What are the food sources for deep-sea life?\"\n",
            "Related search terms: ['Deep-sea fish', 'Deep-sea wood', 'Deep sea']\n",
            "Fetching page: \"Deep-sea wood\"\n",
            "Information Source: https://en.wikipedia.org/wiki/Deep-sea_wood\n",
            "Searching for \"How do deep-sea organisms survive in the absence of sunlight?\"\n",
            "Related search terms: ['Deep-sea community', 'Hydrothermal vent', 'Abyssal zone']\n",
            "Fetching page: \"Deep-sea community\"\n",
            "Information Source: https://en.wikipedia.org/wiki/Deep-sea_community\n",
            "Fetching page: \"Hydrothermal vent\"\n",
            "Information Source: https://en.wikipedia.org/wiki/Hydrothermal_vent\n",
            "Fetching page: \"Abyssal zone\"\n",
            "Information Source: https://en.wikipedia.org/wiki/Abyssal_zone\n",
            "Searching for \"What are the unique adaptations of deep-sea animals?\"\n",
            "Related search terms: ['Deep sea', 'Deep-sea community', 'Deep-sea fish']\n",
            "Searching for \"Deep-sea hydrothermal vents and life\"\n",
            "Related search terms: ['Hydrothermal vent', 'Deep-sea community', 'Hydrothermal vent microbial communities']\n",
            "Fetching page: \"Hydrothermal vent microbial communities\"\n",
            "Information Source: https://en.wikipedia.org/wiki/Hydrothermal_vent_microbial_communities\n",
            "Searching for \"Deep-sea chemosynthesis\"\n",
            "Related search terms: ['Deep-sea community', 'Deep sea', 'Hydrothermal vent']\n",
            "Searching for \"Bioluminescence in deep-sea creatures\"\n",
            "Related search terms: ['Deep-sea community', 'Deep sea', 'Deep-sea fish']\n",
            "Searching for \"Deep-sea extremophiles survival mechanisms\"\n",
            "Related search terms: ['Hydrothermal vent', 'Extremophile', 'Deep-sea community']\n",
            "Fetching page: \"Extremophile\"\n",
            "Information Source: https://en.wikipedia.org/wiki/Extremophile\n",
            "Searching for \"How do deep-sea fish regulate buoyancy?\"\n",
            "Related search terms: ['Deep sea', 'Deep sea mining', 'Neutral buoyancy']\n",
            "Fetching page: \"Deep sea mining\"\n",
            "Information Source: https://en.wikipedia.org/wiki/Deep_sea_mining\n",
            "Fetching page: \"Neutral buoyancy\"\n",
            "Information Source: https://en.wikipedia.org/wiki/Neutral_buoyancy\n",
            "Searching for \"What is marine snow and its role in deep-sea ecosystems?\"\n",
            "Related search terms: ['Deep-sea community', 'Deep-sea fish', 'Deep sea']\n",
            "Information Sources:\n",
            "     https://en.wikipedia.org/wiki/Deep_sea\n",
            "     https://en.wikipedia.org/wiki/Deep-sea_fish\n",
            "     https://en.wikipedia.org/wiki/Oceanic_zone\n",
            "     https://en.wikipedia.org/wiki/Deep-sea_wood\n",
            "     https://en.wikipedia.org/wiki/Deep-sea_community\n",
            "     https://en.wikipedia.org/wiki/Hydrothermal_vent\n",
            "     https://en.wikipedia.org/wiki/Abyssal_zone\n",
            "     https://en.wikipedia.org/wiki/Hydrothermal_vent_microbial_communities\n",
            "     https://en.wikipedia.org/wiki/Extremophile\n",
            "     https://en.wikipedia.org/wiki/Deep_sea_mining\n",
            "     https://en.wikipedia.org/wiki/Neutral_buoyancy\n"
          ]
        }
      ],
      "source": [
        "summaries = wikipedia_search(**fc['args'])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "kv4WGnG_gT3F"
      },
      "source": [
        "Now send the `FunctionResult` to the model."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 65,
      "metadata": {
        "id": "bcLuieHqj9PW"
      },
      "outputs": [
        {
          "name": "stderr",
          "output_type": "stream",
          "text": [
            "Warning: there are non-text parts in the response: ['thought_signature'], returning concatenated text result from text parts. Check the full candidates.content.parts accessor to get the full model response.\n"
          ]
        },
        {
          "data": {
            "text/markdown": [
              "> Deep-sea life has evolved a remarkable array of adaptations to survive in an environment characterized by extreme pressure, perpetual darkness, scarce food, and often unique chemical conditions.\n",
              "> \n",
              "> Here's how they manage to thrive:\n",
              "> \n",
              "> 1.  **Adapting to Immense Pressure:**\n",
              ">     *   **Internal Pressure Equalization:** Deep-sea organisms maintain an internal pressure that matches the crushing external hydrostatic pressure, preventing their bodies from being compressed.\n",
              ">     *   **Protein Stability:** Their proteins have evolved unique structural changes, such as increased salt bridges and more rigid globular structures, to maintain functionality under high pressure. Specific osmolytes like Trimethylamine N-oxide (TMAO) are also abundant in their cells to protect proteins from destabilization.\n",
              ">     *   **Membrane Fluidity:** To counteract the reduced fluidity of cell membranes under pressure, they increase the proportion of unsaturated fatty acids in their membrane lipids, ensuring essential biological processes can occur efficiently.\n",
              ">     *   **Skeletal and Tissue Modifications:** Many deep-sea fish have reduced tissue density, minimal bone structure, and gelatinous, water-filled bodies. This helps them with buoyancy and withstands the constant pressure. Unlike shallow-water fish, most deep-sea species do not have gas-filled swim bladders, as these would be crushed by the pressure. Some may develop a gelatinous layer for buoyancy and to reduce drag.\n",
              "> \n",
              "> 2.  **Finding Food and Energy in Perpetual Darkness:**\n",
              ">     *   **Marine Snow and Large Food Falls:** With no sunlight for photosynthesis, the primary food source for many deep-sea creatures is \"marine snow\"—a continuous shower of organic particles (dead organisms, waste, detritus) sinking from the productive upper ocean layers. Larger, less frequent food sources include \"whale falls,\" where the carcasses of dead whales provide a massive, long-lasting feast for specialized communities.\n",
              ">     *   **Chemosynthesis:** At hydrothermal vents and cold seeps, entire ecosystems flourish independently of sunlight. Here, specialized bacteria perform chemosynthesis, using chemical compounds (like hydrogen sulfide, methane, and other minerals) released from the Earth's interior as an energy source to produce organic matter. These chemosynthetic bacteria form the base of the food web, supporting a diverse array of life, including giant tube worms, clams, and mussels, many of which host these bacteria in symbiotic relationships within their bodies.\n",
              ">     *   **Vertical Migration:** Some mid-water (mesopelagic) species undertake daily vertical migrations, ascending to the more food-rich surface waters at night to feed and returning to the darker, safer depths during the day.\n",
              "> \n",
              "> 3.  **Coping with Darkness and Sensing the Environment:**\n",
              ">     *   **Sensory Adaptations:** Many deep-sea organisms have either evolved extremely large, highly sensitive eyes to detect the faintest light (including bioluminescence) or have lost their eyes entirely, relying instead on enhanced senses of touch, smell, and pressure changes to navigate, find food, and avoid predators.\n",
              ">     *   **Bioluminescence:** The ability to produce their own light (bioluminescence) is widespread. It's used for various purposes: attracting mates or prey, startling or distracting predators (e.g., creating a \"smokescreen\"), and camouflage through counter-illumination (matching the faint downwelling light to hide their silhouette).\n",
              ">     *   **Coloration:** Due to the absence of light, vibrant colors are not visible. Many deep-sea creatures are transparent, black, or red. Red appears black in the deep ocean because red light wavelengths are absorbed quickly by water and do not penetrate to these depths, providing effective camouflage.\n",
              "> \n",
              "> 4.  **Metabolic and Behavioral Strategies:**\n",
              ">     *   **Slow Metabolism:** To conserve energy in an environment with limited food resources, many deep-sea organisms have significantly slower metabolic rates and require less oxygen.\n",
              ">     *   **Energy Conservation:** Movement is often slow and deliberate. Reproduction rates are also typically slow, which reduces competition for scarce resources.\n",
              ">     *   **Efficient Feeding:** Many species have large, flexible mouths and expandable stomachs, allowing them to consume large, infrequent meals when prey is encountered, maximizing the intake from rare opportunities.\n",
              "> \n",
              "> 5.  **Extremophile Specializations:**\n",
              ">     *   Microorganisms thriving in the most extreme deep-sea conditions (extremophiles) exhibit highly specialized survival mechanisms. Their amino acid compositions allow their proteins to function under extreme temperatures and pressures. They have unique metabolic pathways, such as sulfur oxidation, hydrocarbon bioremediation, or even \"eating rocks\" (like pyrite), enabling them to derive energy from unusual chemical sources in their harsh habitats."
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "execution_count": 65,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "response = chat.send_message(\n",
        "    [genai.types.Part.from_function_response(\n",
        "        name='wikipedia_search',\n",
        "        response={'result': summaries}\n",
        "    )]\n",
        ")\n",
        "\n",
        "to_markdown(response.text)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "L2Vfv8xpmuV1"
      },
      "source": [
        "## Re-ranking the search results"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "cQ3JUJLeGGzA"
      },
      "source": [
        "Helper function to embed the content:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 69,
      "metadata": {
        "id": "mSkE7EynJBwF"
      },
      "outputs": [],
      "source": [
        "EMBEDDINGS_MODEL_ID = \"gemini-embedding-001\"  # @param [\"gemini-embedding-001\", \"text-embedding-004\"] {\"allow-input\": true, \"isTemplate\": true}\n",
        "\n",
        "def get_embeddings(content: list[str]) -> np.ndarray:\n",
        "  embeddings = client.models.embed_content(\n",
        "    model=EMBEDDINGS_MODEL_ID,\n",
        "    contents=content,\n",
        "    config=types.EmbedContentConfig(\n",
        "      task_type='SEMANTIC_SIMILARITY'\n",
        "    )\n",
        "  )\n",
        "  return embeddings.embeddings[0].values"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "tip8ArqJf_ep"
      },
      "source": [
        "Please refer to the [embeddings guide](https://ai.google.dev/gemini-api/docs/embeddings) for more information on embeddings."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "nSPyycFuFj-_"
      },
      "source": [
        "Your next step is to define functions that you can use to calculate similarity scores between two embedding vectors. These scores will help you decide which embedding vector is the most relevant vector to the user's query.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ltbB0vDsKQtI"
      },
      "source": [
        "You will now implement cosine similarity as your metric. Here returned embedding vectors will be of unit length and hence their L1 norm (`np.linalg.norm()`) will be ~1. Hence, calculating cosine similarity is esentially same as calculating their dot product score."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 76,
      "metadata": {
        "id": "9iDFdzq_JWJW"
      },
      "outputs": [],
      "source": [
        "def dot_product(a: np.ndarray, b: np.ndarray):\n",
        "  return (np.array(a) @ np.array(b).T)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "MrF_1c_M_Hw3"
      },
      "source": [
        "### Similarity with user's query\n",
        "\n",
        "Now it's time to find the most relevant search result returned by the Wikipedia API.\n",
        "\n",
        "Use Gemini API to get embeddings for user's query and search results."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 70,
      "metadata": {
        "id": "gK9ryjftGDNe"
      },
      "outputs": [],
      "source": [
        "search_res = get_embeddings(summaries)\n",
        "embedded_query = get_embeddings([query])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "2wwWq30uGRG3"
      },
      "source": [
        "Calculate similarity score:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 77,
      "metadata": {
        "id": "jWlFNYIsGV0X"
      },
      "outputs": [],
      "source": [
        "sim_value = dot_product(search_res, embedded_query)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "bJW1pQQXG2w2"
      },
      "source": [
        "using `np.argmax` best candidate is selected.\n",
        "\n",
        "**Users's Input:** Explain how deep-sea life survives.\n",
        "\n",
        "**Answer:**"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 79,
      "metadata": {
        "id": "8vDMDnCsG8Wn"
      },
      "outputs": [
        {
          "data": {
            "text/markdown": [
              "Here's the extracted information about how deep-sea creatures adapt to high pressure:\n",
              "\n",
              "*   Deep-sea fish have different adaptations in their proteins, anatomical structures, and metabolic systems to survive in the Deep sea, where the inhabitants have to withstand great amount of hydrostatic pressure.\n",
              "*   Deep-sea organisms must have the ability to maintain a well-regulated metabolic system in the face of high pressures.\n",
              "*   Deep sea species must undergo physiological and structural adaptations to preserve protein functionality against pressure, as hydrostatic pressure affects both protein folding and assembly and enzymatic activity.\n",
              "*   Some Deep-sea fish developed pressure tolerance through the change in mechanism of their α-actin, a protein essential for different cellular functions and a main component for muscle fiber.\n",
              "*   In some species that live in depths greater than 5 km (3.1 mi), C.armatus and C.yaquinae have specific substitutions (e.g., Q137K and V54A from C.armatus or I67P from C.yaquinae) on the active sites of α-Actin, which are predicted to have importance in pressure tolerance.\n",
              "*   These specific substitutions result in significant changes in the salt bridge patterns of the protein, allowing for better stabilization in ATP binding and subunit arrangement. Deep sea fish have more salt bridges in their actins compared to fish inhabiting the upper zones of the sea.\n",
              "*   Specific osmolytes were found to be abundant in deep sea fish under high hydrostatic pressure. For certain chondrichthyans, Trimethylamine N-oxide (TMAO) increased with depth, replacing other osmolytes and urea. TMAO is able to protect proteins from high hydrostatic pressure destabilizing them.\n",
              "*   The Mariana hadal snailfish developed modification in the Osteocalcin(burlap) gene, where premature termination was found, resulting in an open skull and cartilage-based bone formation. This is an adaptation because closed skulls common in surface organisms cannot withstand the enforcing stress of high hydrostatic pressure, and common bone developments cannot maintain structural integrity under constant high pressure.\n",
              "\n",
              "Based on:\n",
              "  https://en.wikipedia.org/wiki/Deep_sea"
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "execution_count": 79,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "Markdown(summaries[np.argmax(sim_value)])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Ozn6mIFvoyJU"
      },
      "source": [
        "### Similarity with Hypothetical Document Embeddings (HyDE)\n",
        "\n",
        "Drawing inspiration from [Gao et al](https://arxiv.org/abs/2212.10496) the objective here is to generate a template answer to the user's query using `gemini-2.5-flash`'s internal knowledge. This hypothetical answer will serve as a baseline to calculate relevance of all the search results."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 81,
      "metadata": {
        "id": "J7m5KAkMREBH"
      },
      "outputs": [
        {
          "data": {
            "text/markdown": [
              "> Oh, deep-sea life, that's truly fascinating! It's like a whole other planet down there, and they've evolved some utterly incredible ways to just... exist.\n",
              "> \n",
              "> First off, the **[immense environmental force]** is immense, right? It's not like anything we experience up here. So, deep-sea creatures have these really special **[type of internal structure or biological compound]** that prevents their cells from just collapsing. Their **[specific body parts or tissues]** are incredibly flexible yet strong, designed to withstand those crushing forces. It’s not just about being squishy; it's about their **[molecular processes]** being able to function perfectly under that extreme compression.\n",
              "> \n",
              "> Then there's the **[lack of primary resource]**, which is probably the biggest challenge after pressure. No sunlight means no photosynthesis. So, they've come up with some truly ingenious ways to get energy. Many just rely on whatever **[type of organic matter]** floats down from the **[upper ocean layer]**, basically scavenging. Others, near **[geological features]**, have developed **[type of metabolic process]** where they get energy from **[specific chemical compounds A]** and **[specific chemical compounds B]** spewing out of the Earth – completely independent of the sun! It's wild.\n",
              "> \n",
              "> And speaking of no light, they don't have typical eyes in many cases, or if they do, they're adapted to pick up the faintest **[type of light emission]**. Many rely on other senses entirely, like detecting **[subtle environmental cues]** or **[specific chemical signals]** in the water. Plus, a lot of them use **[biological light production]** for communication, attracting mates, or even luring prey. Imagine a world where your only light source is your own body or your neighbor's!\n",
              "> \n",
              "> The **[temperature extreme]** is another hurdle. It's usually bone-chillingly cold down there. So, they often have **[biological compounds]** in their bodies that act like natural antifreeze, keeping their **[bodily fluids]** from freezing solid. Their **[metabolic rate]** is also often incredibly slow, which helps them conserve energy in such a resource-scarce and cold environment.\n",
              "> \n",
              "> Finding a mate in the vast, dark emptiness? That's a puzzle! They've got strategies like releasing **[specific chemical attractants]** that drift for miles, or using unique patterns of **[biological light]** to signal their presence. Some are even **[reproductive strategy]**, so they don't have to worry about finding another gender.\n",
              "> \n",
              "> It really goes to show how life finds a way, doesn't it? They've just adapted their entire existence around these extreme conditions."
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "execution_count": 81,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "res = client.models.generate_content(\n",
        "    model=MODEL_ID,\n",
        "    contents=f\"\"\"Generate a hypothetical answer\n",
        "to the user's query by using your own knowledge. Assume that you know everything\n",
        "about the said topic. Do not use factual information, instead use placeholders\n",
        "to complete your answer. Your answer should feel like it has been written by a human.\n",
        "\n",
        "query: {query}\"\"\")\n",
        "\n",
        "to_markdown(res.text)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "85f4MpLgrYbW"
      },
      "source": [
        "Use Gemini API to get embeddings for the baseline answer and compare them with search results"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 82,
      "metadata": {
        "id": "fSI6-5eYI3me"
      },
      "outputs": [],
      "source": [
        "hypothetical_ans = get_embeddings([res.text])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "WxYGEWbqrh44"
      },
      "source": [
        "Calculate similarity scores to rank the search results"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 83,
      "metadata": {
        "id": "99sjvMtlJfL_"
      },
      "outputs": [],
      "source": [
        "sim_value = dot_product(search_res, hypothetical_ans)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 84,
      "metadata": {
        "id": "C32IhIapQFNa"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "0.8530243497361725"
            ]
          },
          "execution_count": 84,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "sim_value"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "wJ7pklxursSk"
      },
      "source": [
        "using `np.argmax` best candidate is selected.\n",
        "\n",
        "**Users's Input:** Explain how deep-sea life survives.\n",
        "\n",
        "**Answer:**"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 85,
      "metadata": {
        "id": "MzTfyU_mJ8-M"
      },
      "outputs": [
        {
          "data": {
            "text/markdown": [
              "> Here's the extracted information about how deep-sea creatures adapt to high pressure:\n",
              "> \n",
              "> *   Deep-sea fish have different adaptations in their proteins, anatomical structures, and metabolic systems to survive in the Deep sea, where the inhabitants have to withstand great amount of hydrostatic pressure.\n",
              "> *   Deep-sea organisms must have the ability to maintain a well-regulated metabolic system in the face of high pressures.\n",
              "> *   Deep sea species must undergo physiological and structural adaptations to preserve protein functionality against pressure, as hydrostatic pressure affects both protein folding and assembly and enzymatic activity.\n",
              "> *   Some Deep-sea fish developed pressure tolerance through the change in mechanism of their α-actin, a protein essential for different cellular functions and a main component for muscle fiber.\n",
              "> *   In some species that live in depths greater than 5 km (3.1 mi), C.armatus and C.yaquinae have specific substitutions (e.g., Q137K and V54A from C.armatus or I67P from C.yaquinae) on the active sites of α-Actin, which are predicted to have importance in pressure tolerance.\n",
              "> *   These specific substitutions result in significant changes in the salt bridge patterns of the protein, allowing for better stabilization in ATP binding and subunit arrangement. Deep sea fish have more salt bridges in their actins compared to fish inhabiting the upper zones of the sea.\n",
              "> *   Specific osmolytes were found to be abundant in deep sea fish under high hydrostatic pressure. For certain chondrichthyans, Trimethylamine N-oxide (TMAO) increased with depth, replacing other osmolytes and urea. TMAO is able to protect proteins from high hydrostatic pressure destabilizing them.\n",
              "> *   The Mariana hadal snailfish developed modification in the Osteocalcin(burlap) gene, where premature termination was found, resulting in an open skull and cartilage-based bone formation. This is an adaptation because closed skulls common in surface organisms cannot withstand the enforcing stress of high hydrostatic pressure, and common bone developments cannot maintain structural integrity under constant high pressure.\n",
              "> \n",
              "> Based on:\n",
              ">   https://en.wikipedia.org/wiki/Deep_sea"
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "execution_count": 85,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "to_markdown(summaries[np.argmax(sim_value)])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "UjDN2OUpsL6M"
      },
      "source": [
        "You have now created a search re-ranking engine using embeddings!"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "AKH2vs2Lc1R1"
      },
      "source": [
        "## Next steps\n",
        "\n",
        "I hope you found this example helpful! Check out more examples in the [Gemini API cookbook](https://github.com/google-gemini/cookbook/) to learn more."
      ]
    }
  ],
  "metadata": {
    "colab": {
      "name": "Search_reranking_using_embeddings.ipynb",
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
